package org.onionframework.persistence.dao.projection;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.PropertyProjection;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;

public class HibernateDateStringProjection extends PropertyProjection {

	private static final long serialVersionUID = -3539290043089199732L;

	private DateStringUtils dateStringUtils;
	
	public HibernateDateStringProjection(String prop, boolean grouped,
			String pattern) {
		super(prop, grouped);
		this.dateStringUtils = new DateStringUtils(pattern);
	}

	public HibernateDateStringProjection(String prop, String pattern) {
		this(prop, false, pattern);
	}

	public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery)
			throws HibernateException {
		return new Type[] { StandardBasicTypes.STRING };
	}

	
	public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) {

		StringBuilder sb = new StringBuilder();
		
		String[] cols = criteriaQuery.getColumns(super.getPropertyName(),
				criteria);
		if (cols.length > 1)
			throw new RuntimeException(
					"Hibernate DateString Projection can only process one column.");
		
		sb.append(this.dateStringUtils.toSql(cols[0])).append(" as y").append(position + 0).append('_');
		
		return sb.toString();
	}

	public String toGroupSqlString(Criteria criteria,
			CriteriaQuery criteriaQuery) throws HibernateException {
		
		String[] cols = criteriaQuery.getColumns(super.getPropertyName(),
				criteria);
		
		if (cols.length > 1)
			throw new RuntimeException(
					"Hibernate DateString Projection can only process one column.");
		
		return this.dateStringUtils.toSql(cols[0]).toString();
	}

}
